"""
@author: Sergiy Tsymbalyuk
"""

import logging

from pylons import tmpl_context as c, request, url
from pylons.controllers.util import redirect, abort

from webhelpers.html.tags import select

from chowa.lib.site.forms import TabularFieldSet
from chowa.model.organization import Division
from hrms.model.organization import Order, Dismissal, Appointment
from hrms.lib.base import BaseController, render, Session
from hrms.model.person import Employee

log = logging.getLogger(__name__)

class TransferController(BaseController):
    def dismissal(self, id):
        order = Order()
        fs = TabularFieldSet(order, Session)
        fs.configure(include=[fs.type, fs.number, fs.approved])
        
        order_option = request.params.get('order-option')
        if order_option:
            if order_option == 'existing':
                order_id = request.params.get('order')
                order = Session.query(Order).get(order_id)
            elif order_option == 'new':
                fs.rebind(data=request.params)
                fs.sync()
                Session.commit()
            else:
                return abort(404)
            empl_ids = request.params.getall('employees')
            employees = Session.query(Employee).filter(Employee.id.in_(empl_ids)).all()
            for employee in employees:
                dismissal = Dismissal(employee=employee,
                                      division_id=id,
                                      order=order,
                                      position=employee.position,
                                      executed=order.approved)
                Session.add(dismissal)
            Session.commit()
            return redirect(url.current(action='appointment', employees=empl_ids))
        c.division = Session.query(Division).get(id)
        
        orders = Session.query(Order).order_by('approved').all()
        c.select_order = select('order', [], [(o.id, unicode(o))
                                              for o in orders])
        c.order_form = fs.render()
        return render('/hrms/organization/transfer/dismissal.html')

    def appointment(self, id):
        order = Order()
        order_fs = TabularFieldSet(order, Session)
        order_fs.configure(include=[order_fs.type, order_fs.number, order_fs.approved])
        
        division = Division()
        division_fs = TabularFieldSet(division, Session)
        division_fs.configure(include=[division_fs.type, division_fs.name])
        
        order_option = request.params.get('order-option')
        division_option = request.params.get('division-option')
        
        employees = request.params.getall('employees')
        c.employees = Session.query(Employee).filter(Employee.id.in_(employees)).all()
        old_division = Session.query(Division).get(id)
        
        if order_option and division_option:
            # get or create order
            if order_option == 'existing':
                order_id = request.params.get('order')
                order = Session.query(Order).get(order_id)
            elif order_option == 'new':
                order_fs.rebind(data=request.params)
                order_fs.sync()
                Session.commit()
            else:
                return abort(404)
            # get or create division
            if division_option == 'existing':
                division_id = request.params.get('division')
                division = Session.query(Division).get(division_id)
            elif division_option == 'new':
                division_fs.rebind(data=request.params)
                division_fs.sync()
                division.district = old_division.district
                Session.commit()
            else:
                return abort(404)
            # add appointments for each employee
            for employee in c.employees:
                appointment = Appointment(employee=employee,
                                          division=division,
                                          order=order,
                                          position=employee.position,
                                          executed=order.approved)
                Session.add(appointment)
            Session.commit()
            # update current division for employees
            query = Employee.__table__.update() \
                            .values(division_id=division.id) \
                            .where(Employee.id.in_(employees))
            Session.execute(query)
            return redirect(url(controller='career/appointments',
                                action='index',
                                relation='division',
                                id=division.id))
        
        orders = Session.query(Order).order_by('approved').all()
        c.select_order = select('order', [], [(o.id, unicode(o))
                                              for o in orders])
        
        divisions = Session.query(Division).filter_by(district=old_division.district).order_by('name').all()
        c.select_division = select('division', [], [(d.id, unicode(d))
                                                    for d in divisions])
        
        c.order_form = order_fs.render()
        c.division_form = division_fs.render()
        return render('/hrms/organization/transfer/appointment.html')
        